#include "runtimefilesystemwatcher.h"
#include "databasemanager.h"
#include "backendservice.h"
#include "websocketserver.h"
#include <QDebug>
#include <QDir>
#include <QFileInfo>
#include <QRegularExpression>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrl>

// RuntimeWatcherInfo 结构定义
// 关闭句柄的回调函数
static void onRuntimeHandleClose(uv_handle_t* handle) {
    // 句柄已关闭，可以安全删除
    if (handle) {
        uv_fs_event_t* fs_event = reinterpret_cast<uv_fs_event_t*>(handle);
        delete fs_event;
    }
}

struct RuntimeWatcherInfo {
    uv_fs_event_t *handle;
    RuntimeFileSystemWatcher *watcher;
    QString path;
    bool isDirectory;
    bool closing;  // 标记是否正在关闭
    
    RuntimeWatcherInfo() : handle(nullptr), watcher(nullptr), isDirectory(false), closing(false) {}
    
    ~RuntimeWatcherInfo() {
        // 析构函数中不再处理句柄，由 removeWatcher 或 removeAllWatchers 负责
    }
};

RuntimeFileSystemWatcher::RuntimeFileSystemWatcher(QObject *parent)
    : QObject(parent)
    , m_loop(nullptr)
    , m_eventLoopThread(nullptr)
    , m_stopping(false)
    , m_databaseManager(nullptr)
    , m_backendService(nullptr)
    , m_webSocketServer(nullptr)
    , m_networkManager(new QNetworkAccessManager(this))
{
    // 构建 runtime 目录路径
    m_runtimeDirectory = buildRuntimeDirectory();
    
    // 连接网络请求完成信号
    connect(m_networkManager, &QNetworkAccessManager::finished,
            this, &RuntimeFileSystemWatcher::handleUploadResponse);
    
    qDebug() << "RuntimeFileSystemWatcher 初始化完成，runtime 目录:" << m_runtimeDirectory;
}

void RuntimeFileSystemWatcher::setDatabaseManager(DatabaseManager *dbManager)
{
    m_databaseManager = dbManager;
    qDebug() << "RuntimeFileSystemWatcher 设置数据库管理器";
}

void RuntimeFileSystemWatcher::setBackendService(BackendService *backendService)
{
    m_backendService = backendService;
    qDebug() << "RuntimeFileSystemWatcher 设置 BackendService";
}

void RuntimeFileSystemWatcher::setWebSocketServer(WebSocketServer *webSocketServer)
{
    m_webSocketServer = webSocketServer;
    qDebug() << "RuntimeFileSystemWatcher 设置 WebSocketServer";
}

RuntimeFileSystemWatcher::~RuntimeFileSystemWatcher()
{
    stopWatching();
    stopEventLoop();
    qDebug() << "RuntimeFileSystemWatcher 析构";
}

QString RuntimeFileSystemWatcher::buildRuntimeDirectory() const
{
    // 获取用户主目录
    const QString homeDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
    
    // 构建 runtime 目录路径
    QString runtimeDir = QDir::cleanPath(homeDir + "/.myapps/" + "/runtime");
    
    return runtimeDir;
}

void RuntimeFileSystemWatcher::startWatching()
{
    // 更新 runtime 目录路径（以防主目录改变）
    m_runtimeDirectory = buildRuntimeDirectory();
    
    qDebug() << "RuntimeFileSystemWatcher: 开始监听 runtime 目录:" << m_runtimeDirectory;
    
    // 检查目录是否存在，如果不存在则创建
    QDir dir(m_runtimeDirectory);
    if (!dir.exists()) {
        qDebug() << "RuntimeFileSystemWatcher: runtime 目录不存在，尝试创建:" << m_runtimeDirectory;
        if (!dir.mkpath(m_runtimeDirectory)) {
            qDebug() << "RuntimeFileSystemWatcher: 创建 runtime 目录失败:" << m_runtimeDirectory;
            return;
        }
        qDebug() << "RuntimeFileSystemWatcher: 成功创建 runtime 目录:" << m_runtimeDirectory;
    }
    
    // 确保事件循环已启动
    if (!m_loop) {
        startEventLoop();
    }
    
    // 添加 runtime 目录到监听器
    if (addWatcher(m_runtimeDirectory, true)) {
        qDebug() << "RuntimeFileSystemWatcher: 成功开始监听 runtime 目录:" << m_runtimeDirectory;
    } else {
        qDebug() << "RuntimeFileSystemWatcher: 无法监听 runtime 目录:" << m_runtimeDirectory;
        return;
    }
    
    qDebug() << "RuntimeFileSystemWatcher: 已开始监听 runtime 目录";
}

void RuntimeFileSystemWatcher::stopWatching()
{
    qDebug() << "RuntimeFileSystemWatcher: 停止监听 runtime 目录";
    
    if (!m_runtimeDirectory.isEmpty()) {
        qDebug() << "RuntimeFileSystemWatcher: 当前监听目录:" << m_runtimeDirectory;
        
        // 移除所有监听器
        removeAllWatchers();
        
        qDebug() << "RuntimeFileSystemWatcher: 停止监听目录:" << m_runtimeDirectory;
    } else {
        qDebug() << "RuntimeFileSystemWatcher: 没有正在监听的目录";
    }
}

QString RuntimeFileSystemWatcher::getRuntimeDirectory() const
{
    return m_runtimeDirectory;
}

bool RuntimeFileSystemWatcher::isRuntimeDirectoryExists() const
{
    QDir dir(m_runtimeDirectory);
    return dir.exists();
}

void RuntimeFileSystemWatcher::handleFileCreatedOrChangedEvent(const QString &filePath)
{
    qDebug() << "RuntimeFileSystemWatcher: 处理文件创建或修改事件:" << filePath;
    
    // 检查文件是否在 runtime 目录中
    QString runtimeDir = getRuntimeDirectory();
    QString cleanFilePath = QDir::cleanPath(filePath);
    QString cleanRuntimeDir = QDir::cleanPath(runtimeDir);
    
    if (!cleanFilePath.startsWith(cleanRuntimeDir)) {
        qDebug() << "RuntimeFileSystemWatcher: 文件不在 runtime 目录中，忽略:" << filePath;
        return;
    }
    
    // 这里可以添加额外的处理逻辑
    // 例如：记录日志、通知其他组件等
    qDebug() << "RuntimeFileSystemWatcher: 文件在 runtime 目录中，已处理:" << filePath;
    
    // 发出文件变化信号
    emit filesChanged();
}

void RuntimeFileSystemWatcher::handleFileRemovedEvent(const QString &filePath)
{
    qDebug() << "RuntimeFileSystemWatcher: 处理文件删除事件:" << filePath;
    
    // 检查文件是否在 runtime 目录中（即使文件已删除，也可以检查路径前缀）
    QString runtimeDir = getRuntimeDirectory();
    QString cleanFilePath = QDir::cleanPath(filePath);
    QString cleanRuntimeDir = QDir::cleanPath(runtimeDir);
    
    if (!cleanFilePath.startsWith(cleanRuntimeDir)) {
        qDebug() << "RuntimeFileSystemWatcher: 文件不在 runtime 目录中，忽略:" << filePath;
        return;
    }
    
    // 检查文件名是否匹配正则表达式：
    // ^~\$.*\.docx$ 或 ^~\$.*\.xlsx$ 或 ^~\$.*\.pptx$ 
    // 或 ^~\$.*\.doc$ 或 ^~\$.*\.xls$ 或 ^~\$.*\.ppt$
    QRegularExpression regex("^~\\$.*\\.(docx|xlsx|pptx|doc|xls|ppt)$");
    QRegularExpressionMatch match = regex.match(QFileInfo(filePath).fileName());
    
    if (match.hasMatch()) {
        qDebug() << "RuntimeFileSystemWatcher: 检测到临时文件删除，文件名匹配正则:" << QFileInfo(filePath).fileName();
        
        // 替换掉 ~$ 字符，获取原始文件路径
        QString originalFilePath = filePath;
        originalFilePath.replace("~$", "%");
        // 统一路径分隔符，确保匹配正确
        originalFilePath = QDir::cleanPath(originalFilePath);
        originalFilePath = originalFilePath.replace('\\', '/');
        
        qDebug() << "RuntimeFileSystemWatcher: 处理后的文件路径（去掉~$）:" << originalFilePath;
        
        // 在 kms_command 表中查找匹配的命令记录
        if (m_databaseManager) {
            // 使用尾部匹配查找 LOCAL_FILE_PATH
            // 注意：kms_command.local_file_path 存放为完整路径，所以使用尾部匹配
            KmsCommand command = m_databaseManager->queryCommandByLocalFilePath(originalFilePath);
            
            if (!command.id.isEmpty()) {
                qDebug() << "RuntimeFileSystemWatcher: 找到匹配的命令记录，ID:" << command.id 
                         << "命令:" << command.command
                         << "提交URL:" << command.commitUrl
                         << "文件地址:" << command.localFilePath
                    ;
                
                // 使用 command.commitUrl 提交位于 command.localFilePath 的文件
                if (!command.commitUrl.isEmpty() && !command.localFilePath.isEmpty()) {
                    qDebug() << "RuntimeFileSystemWatcher: 开始提交文件，URL:" << command.commitUrl 
                             << "文件路径:" << command.localFilePath
                             << "accessToken:" << (command.accessToken.isEmpty() ? "空" : "已提供");
                    commitFileToUrl(command.commitUrl, command.localFilePath, command.accessToken);
                } else {
                    qDebug() << "RuntimeFileSystemWatcher: 命令记录缺少提交URL或文件路径";
                    if (command.commitUrl.isEmpty()) {
                        qDebug() << "RuntimeFileSystemWatcher: 提交URL为空";
                    }
                    if (command.localFilePath.isEmpty()) {
                        qDebug() << "RuntimeFileSystemWatcher: 文件路径为空";
                    }
                }
            } else {
                qDebug() << "RuntimeFileSystemWatcher: 未找到匹配的命令记录，文件路径:" << originalFilePath;
            }
        } else {
            qDebug() << "RuntimeFileSystemWatcher: 数据库管理器未设置，无法查询命令记录";
        }
    }
    
    // 发出文件变化信号
    emit filesChanged();
}

bool RuntimeFileSystemWatcher::isFileInRuntimeDirectory(const QString &filePath) const
{
    if (m_runtimeDirectory.isEmpty() || filePath.isEmpty()) {
        return false;
    }
    
    QString cleanFilePath = QDir::cleanPath(filePath);
    QString cleanRuntimeDir = QDir::cleanPath(m_runtimeDirectory);
    return cleanFilePath.startsWith(cleanRuntimeDir);
}

void RuntimeFileSystemWatcher::startEventLoop()
{
    if (m_loop) {
        qDebug() << "RuntimeFileSystemWatcher: 事件循环已存在";
        return;
    }

    qDebug() << "RuntimeFileSystemWatcher: 创建 libuv 事件循环";
    m_loop = new uv_loop_t;
    if (uv_loop_init(m_loop) != 0) {
        qDebug() << "RuntimeFileSystemWatcher: 初始化事件循环失败";
        delete m_loop;
        m_loop = nullptr;
        return;
    }

    // 创建线程运行事件循环
    m_eventLoopThread = QThread::create([this]() {
        this->runEventLoop();
    });
    m_eventLoopThread->start();

    qDebug() << "RuntimeFileSystemWatcher: libuv 事件循环线程已启动";
}

void RuntimeFileSystemWatcher::stopEventLoop()
{
    if (!m_loop) {
        return;
    }

    qDebug() << "RuntimeFileSystemWatcher: 停止 libuv 事件循环";
    m_stopping = true;

    // 先移除所有监听器（这会关闭所有句柄）
    removeAllWatchers();

    // 等待线程结束
    if (m_eventLoopThread && m_eventLoopThread->isRunning()) {
        uv_stop(m_loop);
        m_eventLoopThread->wait(5000); // 最多等待5秒
        
        if (m_eventLoopThread->isRunning()) {
            qDebug() << "RuntimeFileSystemWatcher: 警告：事件循环线程未在5秒内结束";
        }
        
        delete m_eventLoopThread;
        m_eventLoopThread = nullptr;
    }

    // 在主线程中运行事件循环以处理剩余的关闭回调
    int loopAlive = uv_loop_alive(m_loop);
    if (loopAlive) {
        qDebug() << "RuntimeFileSystemWatcher: 事件循环仍有活动句柄，运行以处理关闭回调";
        while (uv_loop_alive(m_loop)) {
            uv_run(m_loop, UV_RUN_ONCE);
            QThread::msleep(10);
        }
    }

    // 关闭事件循环
    int result = uv_loop_close(m_loop);
    if (result != 0) {
        qDebug() << "RuntimeFileSystemWatcher: 关闭事件循环警告，返回值:" << result << uv_strerror(result);
    }
    
    delete m_loop;
    m_loop = nullptr;

    qDebug() << "RuntimeFileSystemWatcher: libuv 事件循环已停止";
}

void RuntimeFileSystemWatcher::runEventLoop()
{
    qDebug() << "RuntimeFileSystemWatcher: 事件循环线程开始运行";
    while (!m_stopping && m_loop) {
        uv_run(m_loop, UV_RUN_ONCE);
        QThread::msleep(10); // 避免CPU占用过高
    }
    qDebug() << "RuntimeFileSystemWatcher: 事件循环线程结束";
}

bool RuntimeFileSystemWatcher::addWatcher(const QString &path, bool isDirectory)
{
    if (!m_loop) {
        qDebug() << "RuntimeFileSystemWatcher: 事件循环未启动，无法添加监听";
        return false;
    }

    QString cleanPath = QDir::cleanPath(path);
    
    // 检查是否已存在
    {
        QMutexLocker locker(&m_watchersMutex);
        if (m_watchers.contains(cleanPath)) {
            qDebug() << "RuntimeFileSystemWatcher: 路径已在监听中:" << cleanPath;
            return true;
        }
    }

    // 创建 RuntimeWatcherInfo
    RuntimeWatcherInfo *info = new RuntimeWatcherInfo;
    info->watcher = this;
    info->path = cleanPath;
    info->isDirectory = isDirectory;
    info->handle = new uv_fs_event_t;

    // 初始化 handle
    int r = uv_fs_event_init(m_loop, info->handle);
    if (r != 0) {
        qDebug() << "RuntimeFileSystemWatcher: 初始化 fs_event 失败:" << uv_strerror(r);
        delete info->handle;
        delete info;
        return false;
    }

    // 设置数据指针
    info->handle->data = info;

    // 转换为 UTF-8 字节数组
    QByteArray pathBytes = cleanPath.toUtf8();
    const char *pathStr = pathBytes.constData();

    // 启动监听，对目录使用递归标志
    unsigned int flags = 0;
    if (isDirectory) {
        flags = UV_FS_EVENT_RECURSIVE;
        qDebug() << "RuntimeFileSystemWatcher: 使用递归标志监听目录:" << cleanPath;
    }
    
    r = uv_fs_event_start(info->handle, onFsEvent, pathStr, flags);
    if (r != 0) {
        qDebug() << "RuntimeFileSystemWatcher: 启动 fs_event 失败:" << uv_strerror(r) << "路径:" << cleanPath;
        delete info->handle;
        delete info;
        return false;
    }

    // 添加到映射
    {
        QMutexLocker locker(&m_watchersMutex);
        m_watchers[cleanPath] = info;
    }

    qDebug() << "RuntimeFileSystemWatcher: 成功添加监听:" << cleanPath << (isDirectory ? "(目录)" : "(文件)");
    return true;
}

void RuntimeFileSystemWatcher::removeWatcher(const QString &path)
{
    QString cleanPath = QDir::cleanPath(path);
    
    RuntimeWatcherInfo *info = nullptr;
    {
        QMutexLocker locker(&m_watchersMutex);
        if (m_watchers.contains(cleanPath)) {
            info = m_watchers.take(cleanPath);
        }
    }

    if (info) {
        if (info->handle && m_loop && !info->closing) {
            info->closing = true;
            uv_fs_event_stop(info->handle);
            info->handle->data = nullptr;
            uv_close(reinterpret_cast<uv_handle_t*>(info->handle), onRuntimeHandleClose);
            info->handle = nullptr;
        }
        delete info;
        qDebug() << "RuntimeFileSystemWatcher: 成功移除监听:" << cleanPath;
    }
}

void RuntimeFileSystemWatcher::removeAllWatchers()
{
    QList<RuntimeWatcherInfo*> watchers;
    {
        QMutexLocker locker(&m_watchersMutex);
        watchers = m_watchers.values();
        m_watchers.clear();
    }

    for (RuntimeWatcherInfo *info : watchers) {
        if (info->handle && m_loop && !info->closing) {
            info->closing = true;
            uv_fs_event_stop(info->handle);
            info->handle->data = nullptr;
            uv_close(reinterpret_cast<uv_handle_t*>(info->handle), onRuntimeHandleClose);
            info->handle = nullptr;
        }
        delete info;
    }

    qDebug() << "RuntimeFileSystemWatcher: 已移除所有监听器";
}

void RuntimeFileSystemWatcher::onFsEvent(uv_fs_event_t *handle, const char *filename, int events, int status)
{
    RuntimeWatcherInfo *info = static_cast<RuntimeWatcherInfo*>(handle->data);
    if (!info || !info->watcher || info->closing) {
        return;
    }

    if (status != 0) {
        qDebug() << "RuntimeFileSystemWatcher: fs_event 错误:" << uv_strerror(status);
        return;
    }

    RuntimeFileSystemWatcher *watcher = info->watcher;
    QString path = info->path;
    
    // 构建完整路径
    QString fullPath = path;
    if (filename && strlen(filename) > 0) {
        if (!path.endsWith('/') && !path.endsWith('\\')) {
            fullPath += "/";
        }
        fullPath += QString::fromUtf8(filename);
    }

    // 判断事件类型
    bool isRename = (events & UV_RENAME) != 0;
    bool isChange = (events & UV_CHANGE) != 0;

    qDebug() << "RuntimeFileSystemWatcher: fs_event 触发 - 路径:" << fullPath 
             << "事件:" << (isRename ? "RENAME" : "") << (isChange ? "CHANGE" : "");

    // 检查 fullPath 是文件还是目录
    bool isFullPathDirectory = false;
    bool isFullPathFile = false;
    
    if (filename && strlen(filename) > 0) {
        QFileInfo fullPathInfo(fullPath);
        if (fullPathInfo.exists()) {
            isFullPathDirectory = fullPathInfo.isDir();
            isFullPathFile = fullPathInfo.isFile();
        } else {
            // 文件不存在，可能是删除操作
            isFullPathFile = true;
        }
    } else {
        isFullPathDirectory = info->isDirectory;
        isFullPathFile = !info->isDirectory;
    }

    // 使用 QMetaObject::invokeMethod 安全地从 libuv 线程调用到 Qt 主线程
    if (isFullPathFile) {
        // 文件变化
        if (isRename || isChange) {
            // 检查路径是否在 runtime 目录内
            bool inRuntimeDir = watcher->isFileInRuntimeDirectory(fullPath);
            
            if (!inRuntimeDir) {
                return;
            }
            
            // 检查文件是否存在
            QFileInfo fileInfo(fullPath);
            bool fileExists = fileInfo.exists() && fileInfo.isFile();
            
            if (!fileExists) {
                // 文件不存在，触发删除事件
                QMetaObject::invokeMethod(watcher, "handleFileRemovedEvent", Qt::QueuedConnection,
                                          Q_ARG(QString, fullPath));
            } else {
                // 文件存在，触发创建或修改事件
                QMetaObject::invokeMethod(watcher, "handleFileCreatedOrChangedEvent", Qt::QueuedConnection,
                                          Q_ARG(QString, fullPath));
            }
        }
    }
    // 目录变化暂时不处理，只关注文件
}

void RuntimeFileSystemWatcher::commitFileToUrl(const QString &commitUrl, const QString &localFilePath, const QString &accessToken)
{
    qDebug() << "RuntimeFileSystemWatcher: 准备提交文件，URL:" << commitUrl << "文件路径:" << localFilePath;
    
    // 验证URL
    if (commitUrl.isEmpty()) {
        qDebug() << "RuntimeFileSystemWatcher: 提交URL为空";
        emit fileCommitCompleted(-1, "提交URL为空");
        return;
    }
    
    // 验证URL格式
    QUrl url(commitUrl);
    if (!url.isValid()) {
        qDebug() << "RuntimeFileSystemWatcher: 无效的提交URL:" << commitUrl;
        emit fileCommitCompleted(-1, "无效的提交URL: " + commitUrl);
        return;
    }
    
    // 验证文件路径
    if (localFilePath.isEmpty()) {
        qDebug() << "RuntimeFileSystemWatcher: 文件路径为空";
        emit fileCommitCompleted(-1, "文件路径为空");
        return;
    }
    
    // 检查文件是否存在
    QFile localFile(localFilePath);
    if (!localFile.exists()) {
        qDebug() << "RuntimeFileSystemWatcher: 本地文件不存在:" << localFilePath;
        emit fileCommitCompleted(-1, "本地文件不存在: " + localFilePath);
        return;
    }
    
    // 读取文件内容
    if (!localFile.open(QIODevice::ReadOnly)) {
        qDebug() << "RuntimeFileSystemWatcher: 无法打开本地文件:" << localFile.errorString();
        emit fileCommitCompleted(-1, "无法打开本地文件: " + localFile.errorString());
        return;
    }
    
    QByteArray fileContent = localFile.readAll();
    localFile.close();
    
    qDebug() << "RuntimeFileSystemWatcher: 文件内容大小:" << fileContent.size() << "字节";
    
    // 创建网络请求
    QNetworkRequest request;
    request.setUrl(url);
    
    // 添加 accessToken 到请求头
    if (!accessToken.isEmpty()) {
        // 如果传入了 accessToken 参数，使用传入的 token
        request.setRawHeader("accessToken", accessToken.toUtf8());
        qDebug() << "RuntimeFileSystemWatcher: 已添加传入的accessToken到请求头";
    } else {
        // 否则从 BackendService 获取 accessToken（作为后备）
        QString tokenFromService;
        if (m_backendService) {
            tokenFromService = m_backendService->getAccessToken();
            if (!tokenFromService.isEmpty()) {
                request.setRawHeader("accessToken", tokenFromService.toUtf8());
                qDebug() << "RuntimeFileSystemWatcher: 已添加BackendService的accessToken到请求头";
            } else {
                qDebug() << "RuntimeFileSystemWatcher: BackendService 的 accessToken 为空";
            }
        } else {
            qDebug() << "RuntimeFileSystemWatcher: BackendService 未设置，无法获取 accessToken";
        }
    }
    
    // 创建多部分数据
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
    
    // 获取文件名
    QFileInfo fileInfo(localFilePath);
    QString fileName = fileInfo.fileName();
    
    // 创建文件部分
    QHttpPart filePart;
    filePart.setHeader(QNetworkRequest::ContentDispositionHeader, 
                      QVariant("form-data; name=\"files\"; filename=\"" + fileName + "\""));
    filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/octet-stream"));
    filePart.setBody(fileContent);
    
    multiPart->append(filePart);
    
    // 发送POST请求
    QNetworkReply *reply = m_networkManager->post(request, multiPart);
    multiPart->setParent(reply); // 确保在reply删除时也删除multiPart
    
    // 设置请求类型标识
    reply->setProperty("requestType", "commitFile");
    reply->setProperty("localFilePath", localFilePath);
    reply->setProperty("commitUrl", commitUrl);
    
    qDebug() << "RuntimeFileSystemWatcher: 文件提交请求已发送，URL:" << commitUrl;
}

void RuntimeFileSystemWatcher::handleUploadResponse(QNetworkReply *reply)
{
    if (!reply) {
        qDebug() << "RuntimeFileSystemWatcher: 上传响应为空";
        emit fileCommitCompleted(-1, "上传响应为空");
        return;
    }
    
    QString requestType = reply->property("requestType").toString();
    if (requestType != "commitFile") {
        // 不是文件提交请求，忽略
        reply->deleteLater();
        return;
    }
    
    QString localFilePath = reply->property("localFilePath").toString();
    QString commitUrl = reply->property("commitUrl").toString();
    
    qDebug() << "RuntimeFileSystemWatcher: 处理文件提交响应，错误:" << reply->error() 
             << "文件路径:" << localFilePath;
    
    if (reply->error() == QNetworkReply::NoError) {
        // 读取响应数据
        QByteArray responseData = reply->readAll();
        qDebug() << "RuntimeFileSystemWatcher: 文件提交成功，响应数据大小:" << responseData.size() << "字节";
        
        // 尝试解析JSON响应
        QJsonParseError parseError;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData, &parseError);
        
        if (parseError.error == QJsonParseError::NoError && jsonDoc.isObject()) {
            QJsonObject response = jsonDoc.object();
            int errcode = response["errcode"].toInt();
            QString errmsg = response["errmsg"].toString();
            
            qDebug() << "RuntimeFileSystemWatcher: 文件提交响应 - errcode:" << errcode << "errmsg:" << errmsg;
            
            // 不管上传是否成功，删除 kms_command 记录
            if (m_databaseManager && !commitUrl.isEmpty()) {
                if (m_databaseManager->deleteCommandByCommitUrl(commitUrl)) {
                    qDebug() << "RuntimeFileSystemWatcher: 成功删除命令记录，提交URL:" << commitUrl;
                } else {
                    qDebug() << "RuntimeFileSystemWatcher: 删除命令记录失败，提交URL:" << commitUrl;
                }
            }

            if (errcode == 0) {
                qDebug() << "RuntimeFileSystemWatcher: 文件提交成功:" << errmsg;               
                // 通过 WebSocket 发送 refresh 消息到客户端
                if (m_webSocketServer) {
                    QJsonObject refreshMessage;
                    refreshMessage["command"] = "refresh";
                    QJsonDocument doc(refreshMessage);
                    QString message = doc.toJson(QJsonDocument::Compact);
                    m_webSocketServer->broadcastMessage(message);
                    qDebug() << "RuntimeFileSystemWatcher: 已通过 WebSocket 发送 refresh 消息到客户端";
                } else {
                    qDebug() << "RuntimeFileSystemWatcher: WebSocketServer 未设置，无法发送 refresh 消息";
                }
                
                emit fileCommitCompleted(0, "文件提交成功: " + errmsg);
            } else {
                qDebug() << "RuntimeFileSystemWatcher: 文件提交失败:" << errmsg;
                emit fileCommitCompleted(errcode, "文件提交失败: " + errmsg);
            }
        } else {
            // 响应不是JSON格式，但请求成功
            qDebug() << "RuntimeFileSystemWatcher: 文件提交响应不是JSON格式，但请求成功";
            
            // 上传成功后，删除 kms_command 记录
            if (m_databaseManager && !commitUrl.isEmpty()) {
                if (m_databaseManager->deleteCommandByCommitUrl(commitUrl)) {
                    qDebug() << "RuntimeFileSystemWatcher: 成功删除命令记录，提交URL:" << commitUrl;
                } else {
                    qDebug() << "RuntimeFileSystemWatcher: 删除命令记录失败，提交URL:" << commitUrl;
                }
            }
            
            emit fileCommitCompleted(0, "文件提交成功");
        }
    } else {
        qDebug() << "RuntimeFileSystemWatcher: 文件提交失败:" << reply->errorString();
        emit fileCommitCompleted(reply->error(), "文件提交失败: " + reply->errorString());
    }
    
    reply->deleteLater();
}

